#!/usr/bin/python
#
# A quick hack to probe for SSL Certificate Information
# Requres python & m2crypto  
# 

import sys
import socket
import string

from M2Crypto import SSL

def reportIP(IPaddress):
	'''
		Funktion, um das SSL Zertifikat des Servers herunterzuladen.  
		Dies geschieht mit Hilfe von M2Crypto.

		M2Crypto bietet die Method ``as_text()`` um die Zertifikat
		in Menschen-lesbare Format auszugeben.
	'''
	
	ctx = SSL.Context()
	ctx.set_allow_unknown_ca(True)
	ctx.set_verify(SSL.verify_none, 1)
	conn = SSL.Connection(ctx)
	conn.postConnectionCheck = None
	timeout = SSL.timeout(15)
	conn.set_socket_read_timeout(timeout)
	conn.set_socket_write_timeout(timeout)
	try:
		sys.stderr.write('Connecting '+IPaddress+'. \n')
		sys.stderr.flush()
		conn.connect((IPaddress, 443))
	except:
		print IPaddress+"|{SSL_HANDSHAKE_FAILED}|"+"|"+"|"+"|"
		sys.stderr.write('failed.\n')
		sys.stderr.flush()
		return
	sys.stderr.write('Getting cert info. \n')
	sys.stderr.flush()

	cert = conn.get_peer_cert()
	#print dir(cert)
	#print cert.as_text()
	#print dir(cert.get_pubkey())
	#print cert.get_pubkey().size()*8
	#print cert.get_pubkey()
	
	return cert.as_text()

if __name__ == "__main__":
	reportIP(sys.argv[1])

